import { Component, OnInit, ViewEncapsulation, ViewChild, OnDestroy } from '@angular/core';
import { Router } from "@angular/router";
import { GoodsService } from "@goods/goods.service";
import { ToolsService } from "@shared/service/tools/tools.service";
import { Subject } from "rxjs/Rx";
import { SeedInfiniteScroll } from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {CouponRespVO} from "@interface/index";
import {EventsService} from "@core/events/events.service";


@Component({
  selector: 'goods-coupon',
  templateUrl: './goods-coupon.component.html',
  styleUrls: ['./goods-coupon.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class GoodsCouponComponent implements OnInit, OnDestroy {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild('modal1') modal1;
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public params = {
    page: 1,
    rows: 10,
  };
  public exchangeCode: string; // 优惠券兑换码
  public coupon: CouponRespVO; // 使用兑换码获取的优惠券
  public couponList: Array<CouponRespVO> = [];  // 我的优惠券列表
  constructor(public router: Router,
              private events: EventsService,
              public goodsService: GoodsService,
              public toolsService: ToolsService ) {
    this.getMyCouponList();
  }

  /**
   * @description 我的优惠券列表
   * @author @zhupw1360
   * @date 2018-01-02
   * @param params {  page , rows }
   */
  getMyCouponList() {
    this.goodsService.getMyCouponList(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.params.page++;
        this.infiniteScroll.complete();
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        this.couponList = [...this.couponList, ...res.data.list];
      }
    });
  }

  // 跳转优惠券说明
  goToCouponExplain() {
    this.router.navigate(['/goods/coupon/explain']);
  }

  goToCouponDetail(codeId) {
    this.router.navigate(['/goods/coupon/', codeId ]);
  }

  /**
   * @description 优惠券兑换功能
   * @author @zhupw1360
   * @date 2018-01-25
   * @param params {  }
   */
  postCouponExchange(exchangeCode: string) {
    this.goodsService.postCouponExchange({exchangeCode: exchangeCode})
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.coupon = res.data;
        this.modal1.show();
      }
      if (!this.exchangeCode) {
        this.toolsService.showToast('请输入兑换码');
      }
      if (res.result !== '0') {
        this.toolsService.showToast('兑换码无效');
      }

    });
  }

  // 关闭模态框
  closeModal() {
    this.events.publish('modal:close');
    this.couponList.unshift(this.coupon);
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
